package com.example.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type;
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.context.annotation.Bean;


@Slf4j
@AutoConfiguration(before = {ErrorMvcAutoConfiguration.class})
@ConditionalOnWebApplication(type = Type.SERVLET)
public class DefaultWebAutoConfiguration {

    @Bean
    public DefaultExceptionHandler defaultExceptionHandler() {
        log.info("DefaultExceptionHandler autoconfig");
        return new DefaultExceptionHandler();
    }

    @Bean
    @ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
    public DefaultErrorController defaultErrorController(ErrorAttributes errorAttributes, ObjectProvider<ErrorViewResolver> errorViewResolvers) {
        log.info("DefaultErrorController autoconfig");
        return new DefaultErrorController(errorAttributes, errorViewResolvers.orderedStream().toList());
    }
}
